"""
WebRTC实时数据处理器
"""
import asyncio
import numpy as np
import logging
from datetime import datetime


async def run(socketio, app, record=False, **kwargs):
    """ 主处理循环 """
    try:
        from go2_webrtc_driver import Go2WebRTCConnection, WebRTCConnectionMethod
        conn = Go2WebRTCConnection(WebRTCConnectionMethod.LocalSTA, ip="192.168.123.161")

        await conn.connect()
        logging.info(">>> GO2已链接 <<<")
        await conn.datachannel.disableTrafficSaving(True)
        conn.datachannel.pub_sub.publish_without_callback("rt/utlidar/switch", "on")

        async def on_lidar_message(message):
            # if not app.config['IS_STREAMING']:
            #     return

            try:
                positions = message["data"]["data"].get("positions", [])
                print(positions)
                points = np.array([positions[i:i + 3] for i in range(0, len(positions), 3)])

                # 更新状态
                app.config['MESSAGE_COUNT'] += 1

                # 发送数据
                socketio.emit('lidar_data', {
                    'points': points.tolist(),
                    'timestamp': datetime.now().isoformat(),
                    'frame_id': app.config['MESSAGE_COUNT']
                })

            except Exception as e:
                print(f"数据处理错误: {str(e)}")

        conn.datachannel.pub_sub.subscribe(
            "rt/utlidar/voxel_map_compressed",
            lambda msg: asyncio.create_task(on_lidar_message(msg))
        )

        while True:
            await asyncio.sleep(1)

    except Exception as e:
        print(f"WebRTC连接错误: {str(e)}")
        await asyncio.sleep(5)